﻿using System;
using System.Data.SqlClient;
using BikeBouncer.BusinessLayer.Entities;
using Devv.Core.UniDataTier;

namespace BikeBouncer.BusinessLayer
{
	public partial class DataAccess
	{
		#region Get

		public static SqlDataReader Note_Get(Int32 id)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@NoteId", id);

			return (SqlDataReader)db.ExecuteReader("upNote_Get");
		}

		public static SqlDataReader Note_Get(Item item, Int32 count)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@ItemId", item.Id);
			db.AddParameter("@Count", count);

			return (SqlDataReader)db.ExecuteReader("upNote_Get");
		}

		public static SqlDataReader Note_Get(Item item, DateTime aroundDate, Int32 count)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@ItemId", item.Id);
			db.AddParameter("@MinPostedDate", aroundDate.AddSeconds(-20));
			db.AddParameter("@MaxPostedDate", aroundDate.AddSeconds(20));

			return (SqlDataReader)db.ExecuteReader("upNote_Get");
		}

		public static SqlDataReader Note_Get(Item item, DateTime minDate, DateTime maxDate, Int32 count)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@ItemId", item.Id);
			db.AddParameter("@MinPostedDate", minDate);
			db.AddParameter("@MaxPostedDate", maxDate);

			return (SqlDataReader)db.ExecuteReader("upNote_Get");
		}

		#endregion

		#region Insert and update

		public static void Note_Insert(Note note)
		{
			using (DataHandler db = new DataHandler())
			{
				db.AddParameter("@ItemId", note.Item.Id);
				db.AddParameter("@IP", note.IP);
				db.AddParameter("@Details", note.Details);
				db.AddParameter("@ReferenceDate", note.ReferenceDate);
				db.AddParameter("@Active", note.Active);

				if (note.User.Id > 0)
				{
					db.AddParameter("@UserId", note.User.Id);
				}

				if (note.Address.Id > 0)
				{
					db.AddParameter("@AddressId", note.Address.Id);
				}

				note.Id = Convert.ToInt32(db.ExecuteScalar("upNote_Insert"));
			}

			MailManager.NoteAdded(note);
		}

		#endregion
	}
}